import React, { useState, useEffect, useCallback } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { 
  Typography, 
  Card, 
  Row, 
  Col, 
  Button,
  Breadcrumb,
  Upload,
  message,
  Modal,
  Tooltip,
  Form,
  Select,
  InputNumber,
  Input
} from 'antd'
import { 
  HomeOutlined,
  FileTextOutlined,
  EditOutlined,
  PlusOutlined,
  UploadOutlined,
  EyeOutlined,
  CloseOutlined
} from '@ant-design/icons'
import { StoryboardProject } from '../../../types/storyboardProject'
import { StoryboardData, ShotType } from '../../../types/document'
import { storyboardProjectService } from '../../../services/storage/storyboardProjectService'

const { Title } = Typography
const { Meta } = Card

interface StoryboardCard {
  id: string
  title: string
  image?: string
  images?: string[]  // 支持多图片
  content: string
  shotType: string
  duration: number
}

/**
 * 故事板视图页面
 * 以卡片形式展示分镜内容，类似传统故事板
 */
const StoryboardViewPage: React.FC = () => {
  const { projectId } = useParams<{ projectId: string }>()
  const navigate = useNavigate()
  
  const [project, setProject] = useState<StoryboardProject | null>(null)
  const [storyboardCards, setStoryboardCards] = useState<StoryboardCard[]>([])
  const [loading, setLoading] = useState(true)
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [currentEditCard, setCurrentEditCard] = useState<StoryboardCard | null>(null)
  
  // 编辑表单状态
  const [editForm, setEditForm] = useState({
    shotType: '',
    duration: 5,
    content: '',
    voiceOver: ''
  })

  // 景别类型中文映射
  const shotTypeLabels = {
    [ShotType.EXTREME_WIDE]: '远景',
    [ShotType.WIDE]: '全景',
    [ShotType.MEDIUM_WIDE]: '中远景',
    [ShotType.MEDIUM]: '中景',
    [ShotType.MEDIUM_CLOSE]: '中近景',
    [ShotType.CLOSE_UP]: '近景',
    [ShotType.EXTREME_CLOSE_UP]: '特写'
  }

  // 获取景别中文名称
  const getShotTypeLabel = useCallback((shotType: string): string => {
    return shotTypeLabels[shotType as ShotType] || '中景'
  }, [])

  // 加载项目数据
  const loadProject = useCallback(async () => {
    console.log('[故事板视图] 开始加载项目，projectId:', projectId)
    
    if (!projectId) {
      console.error('[故事板视图] 项目ID无效，导航回分镜列表')
      message.error('项目ID无效')
      navigate('/storyboard')
      return
    }

    setLoading(true)
    try {
      console.log('[故事板视图] 尝试获取项目数据，ID:', projectId)
      const projectData = await storyboardProjectService.getProjectById(projectId)
      console.log('[故事板视图] 项目数据查询结果:', projectData)
      
      if (!projectData) {
        console.error('[故事板视图] 项目不存在，导航回分镜列表')
        message.error('项目不存在')
        navigate('/storyboard')
        return
      }

      setProject(projectData)
      
      // 获取分镜数据并转换为卡片格式 - 使用与分镜项目页面一致的方法
      const content = await storyboardProjectService.getProjectContent(projectId)
      console.log('[故事板视图] 分镜内容数据:', content)
      
      if (content?.scenes && content.scenes.length > 0) {
        console.log('[故事板视图] 发现场景数据，场景数量:', content.scenes.length)
        
        // 先转换为表格行格式（与分镜项目页面一致）
        const tableRows = content.scenes.map((scene, index) => ({
          id: scene.id,
          order: scene.order || index + 1,
          shotType: scene.shot?.type || 'medium',
          duration: scene.timing?.duration || scene.duration || 5,
          content: scene.description || scene.content || '',
          notes: scene.notes || '',
          title: scene.title || `镜头${index + 1}`,
          image: scene.image || scene.thumbnail // 支持图片字段，包括备用字段
        }))
        
        // 再转换为卡片格式
        const cards: StoryboardCard[] = tableRows.map((row, index) => {
          // 处理多图片数据
          const scene = content.scenes.find(s => s.id === row.id)
          const images = scene?.images || (scene?.image ? [scene.image] : [])
          
          return {
            id: row.id,
            title: row.title,
            image: images[0], // 主图片（第一张）
            images: images, // 所有图片列表
            content: row.content || '无内容',
            shotType: getShotTypeLabel(row.shotType), // 使用中文景别标签
            duration: row.duration || 5
          }
        })
        
        setStoryboardCards(cards)
        console.log('[故事板视图] 卡片数据生成完成，卡片数量:', cards.length)
      } else {
        console.warn('[故事板视图] 未找到场景数据，创建示例卡片')
        // 创建一些示例卡片用于展示
        const exampleCards: StoryboardCard[] = [
          {
            id: 'example_1',
            title: '镜头1',
            image: undefined,
            content: '请点击分镜制作页面添加内容',
            shotType: '中景',
            duration: 5
          }
        ]
        setStoryboardCards(exampleCards)
      }
    } catch (error) {
      console.error('[故事板视图] 加载项目失败:', error)
      message.error('加载项目失败')
      navigate('/storyboard')
    } finally {
      setLoading(false)
    }
  }, [projectId, navigate, getShotTypeLabel])

  useEffect(() => {
    loadProject()
  }, [loadProject])

  // 监听分镜数据更新事件
  useEffect(() => {
    const handleStoryboardUpdate = (event: CustomEvent) => {
      const { projectId: updatedProjectId, updatedData } = event.detail
      
      // 只处理当前项目的更新
      if (updatedProjectId === projectId) {
        console.log('[故事板视图] 接收到数据更新事件，重新加载项目数据')
        loadProject() // 重新加载项目数据
      }
    }

    // 添加事件监听器
    window.addEventListener('storyboard:dataUpdated', handleStoryboardUpdate as EventListener)

    // 清理函数
    return () => {
      window.removeEventListener('storyboard:dataUpdated', handleStoryboardUpdate as EventListener)
    }
  }, [projectId, loadProject])

  // 处理图片预览
  const handleImagePreview = (image: string) => {
    setPreviewImage(image)
    setPreviewVisible(true)
  }

  // 处理图片上传
  const handleImageUpload = (cardId: string, file: File) => {
    if (!validateImageFile(file)) {
      return false
    }
    
    const reader = new FileReader()
    reader.onload = async (e) => {
      const base64 = e.target?.result as string
      
      // 获取当前卡片的图片列表
      const currentCard = storyboardCards.find(card => card.id === cardId)
      const existingImages = currentCard?.images || (currentCard?.image ? [currentCard.image] : [])
      const newImages = [...existingImages, base64]
      
      // 更新本地卡片状态
      setStoryboardCards(prev => 
        prev.map(card => 
          card.id === cardId 
            ? { 
                ...card, 
                image: newImages[0], // 主图片为第一张
                images: newImages // 更新图片列表
              }
            : card
        )
      )
      
      // 同步到后端数据
      try {
        await updateCardImageData(cardId, newImages)
        message.success('图片上传成功')
      } catch (error) {
        console.error('[故事板视图] 图片上传同步失败:', error)
        message.error('图片上传失败')
      }
    }
    reader.readAsDataURL(file)
    return false // 阻止默认上传行为
  }

  // 编辑镜头
  const handleEditCard = (cardId: string) => {
    const card = storyboardCards.find(c => c.id === cardId)
    if (card) {
      setCurrentEditCard(card)
      setEditForm({
        shotType: card.shotType,
        duration: card.duration,
        content: card.content,
        voiceOver: '' // 暂时为空，后续可以扩展
      })
      setEditModalVisible(true)
    }
  }

  // 处理编辑表单提交
  const handleEditSubmit = async () => {
    if (!currentEditCard) return
    
    try {
      // 更新本地卡片数据
      setStoryboardCards(prev => 
        prev.map(card => 
          card.id === currentEditCard.id 
            ? { 
                ...card, 
                shotType: editForm.shotType,
                duration: editForm.duration,
                content: editForm.content
              }
            : card
        )
      )
      
      // 同步更新到后端数据
      await updateCardData(currentEditCard.id, editForm)
      
      setEditModalVisible(false)
      setCurrentEditCard(null)
      message.success('编辑保存成功')
    } catch (error) {
      console.error('[故事板视图] 编辑保存失败:', error)
      message.error('编辑保存失败')
    }
  }

  // 更新卡片数据到后端
  const updateCardData = async (cardId: string, formData: typeof editForm) => {
    if (!projectId) return
    
    try {
      // 获取当前项目内容
      const content = await storyboardProjectService.getProjectContent(projectId)
      if (!content?.scenes) return
      
      // 查找对应的场景并更新
      const updatedScenes = content.scenes.map(scene => {
        if (scene.id === cardId) {
          return {
            ...scene,
            shot: {
              ...scene.shot,
              type: getShotTypeFromLabel(formData.shotType)
            },
            timing: {
              ...scene.timing,
              duration: formData.duration
            },
            description: formData.content,
            content: formData.content
          }
        }
        return scene
      })
      
      // 更新项目内容
      const updatedStoryboard = {
        ...content,
        scenes: updatedScenes,
        totalDuration: updatedScenes.reduce((total, scene) => total + (scene.timing?.duration || scene.duration || 0), 0)
      }
      
      await storyboardProjectService.updateProjectContent(projectId, updatedStoryboard)
      
      // 发送数据更新事件
      window.dispatchEvent(new CustomEvent('storyboard:dataUpdated', {
        detail: { projectId, updatedData: updatedStoryboard }
      }))
      
    } catch (error) {
      console.error('[故事板视图] 更新后端数据失败:', error)
      throw error
    }
  }

  // 将中文景别标签转换为英文枚举值
  const getShotTypeFromLabel = (label: string): string => {
    const labelToType = {
      '远景': ShotType.EXTREME_WIDE,
      '全景': ShotType.WIDE,
      '中远景': ShotType.MEDIUM_WIDE,
      '中景': ShotType.MEDIUM,
      '中近景': ShotType.MEDIUM_CLOSE,
      '近景': ShotType.CLOSE_UP,
      '特写': ShotType.EXTREME_CLOSE_UP
    }
    return labelToType[label as keyof typeof labelToType] || ShotType.MEDIUM
  }

  // 处理编辑弹窗中的图片上传（新增图片）
  const handleEditModalImageUpload = (file: File) => {
    if (!currentEditCard) return false
    
    const reader = new FileReader()
    reader.onload = (e) => {
      const base64 = e.target?.result as string
      
      // 获取现有图片列表
      const existingImages = currentEditCard.images || []
      const newImages = [...existingImages, base64]
      
      // 更新编辑中的卡片数据
      setCurrentEditCard(prev => prev ? { 
        ...prev, 
        images: newImages,
        image: newImages[0] // 主图片保持为第一张
      } : null)
      
      // 同时更新卡片列表中的对应项
      setStoryboardCards(prev => 
        prev.map(card => 
          card.id === currentEditCard.id 
            ? { 
                ...card, 
                images: newImages,
                image: newImages[0]
              }
            : card
        )
      )
      
      // 同步更新到后端
      updateCardImageData(currentEditCard.id, newImages)
      
      message.success('图片添加成功')
    }
    reader.readAsDataURL(file)
    return false
  }

  // 处理编辑弹窗中的单张图片删除
  const handleEditModalImageRemove = (imageIndex: number) => {
    if (!currentEditCard || !currentEditCard.images) return
    
    const updatedImages = currentEditCard.images.filter((_, index) => index !== imageIndex)
    
    // 更新编辑中的卡片数据
    setCurrentEditCard(prev => prev ? { 
      ...prev, 
      images: updatedImages,
      image: updatedImages[0] || undefined // 如果没有图片了，设为undefined
    } : null)
    
    // 同时更新卡片列表中的对应项
    setStoryboardCards(prev => 
      prev.map(card => 
        card.id === currentEditCard.id 
          ? { 
              ...card, 
              images: updatedImages,
              image: updatedImages[0] || undefined
            }
          : card
      )
    )
    
    // 同步更新到后端
    updateCardImageData(currentEditCard.id, updatedImages)
    
    message.success('图片已删除')
  }

  // 手动触发添加图片文件选择
  const handleAddImageClick = () => {
    console.log('[故事板视图] 手动触发添加图片文件选择')
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0]
      if (file) {
        console.log('[故事板视图] 文件已选择:', file.name)
        if (validateImageFile(file)) {
          console.log('[故事板视图] 文件验证通过，开始添加')
          handleEditModalImageUpload(file)
        } else {
          console.log('[故事板视图] 文件验证失败')
        }
      }
    }
    input.click()
  }

  // 手动触发图片替换文件选择
  const handleImageReplaceClick = (imageIndex: number) => {
    console.log('[故事板视图] 手动触发图片替换文件选择，索引:', imageIndex)
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0]
      if (file) {
        console.log('[故事板视图] 文件已选择:', file.name)
        if (validateImageFile(file)) {
          console.log('[故事板视图] 文件验证通过，开始替换')
          handleEditModalImageReplace(imageIndex, file)
        } else {
          console.log('[故事板视图] 文件验证失败')
        }
      }
    }
    input.click()
  }

  // 处理编辑弹窗中的单张图片替换
  const handleEditModalImageReplace = (imageIndex: number, file: File) => {
    if (!currentEditCard || !currentEditCard.images) return false
    
    const reader = new FileReader()
    reader.onload = (e) => {
      const base64 = e.target?.result as string
      
      // 替换指定位置的图片
      const updatedImages = [...currentEditCard.images!]
      updatedImages[imageIndex] = base64
      
      // 更新编辑中的卡片数据
      setCurrentEditCard(prev => prev ? { 
        ...prev, 
        images: updatedImages,
        image: updatedImages[0] // 主图片保持为第一张
      } : null)
      
      // 同时更新卡片列表中的对应项
      setStoryboardCards(prev => 
        prev.map(card => 
          card.id === currentEditCard.id 
            ? { 
                ...card, 
                images: updatedImages,
                image: updatedImages[0]
              }
            : card
        )
      )
      
      // 同步更新到后端
      updateCardImageData(currentEditCard.id, updatedImages)
      
      message.success('图片替换成功')
    }
    reader.readAsDataURL(file)
    return false
  }

  // 处理编辑弹窗中的图片预览
  const handleEditModalImagePreview = (imageUrl: string) => {
    setPreviewImage(imageUrl)
    setPreviewVisible(true)
  }

  // 更新卡片图片数据到后端
  const updateCardImageData = async (cardId: string, imageData: string[] | string) => {
    if (!projectId) return
    
    try {
      // 获取当前项目内容
      const content = await storyboardProjectService.getProjectContent(projectId)
      if (!content?.scenes) return
      
      // 查找对应的场景并更新图片
      const updatedScenes = content.scenes.map(scene => {
        if (scene.id === cardId) {
          const images = Array.isArray(imageData) ? imageData : [imageData].filter(Boolean)
          return {
            ...scene,
            image: images[0] || undefined, // 主图片
            images: images.length > 0 ? images : undefined // 图片列表
          }
        }
        return scene
      })
      
      // 更新项目内容
      const updatedStoryboard = {
        ...content,
        scenes: updatedScenes
      }
      
      await storyboardProjectService.updateProjectContent(projectId, updatedStoryboard)
      
      // 发送数据更新事件
      window.dispatchEvent(new CustomEvent('storyboard:dataUpdated', {
        detail: { projectId, updatedData: updatedStoryboard }
      }))
      
    } catch (error) {
      console.error('[故事板视图] 更新图片数据失败:', error)
    }
  }

  // 验证图片文件
  const validateImageFile = (file: File) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
      message.error('只能上传图片文件!')
      return false
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      message.error('图片大小不能超过5MB!')
      return false
    }
    
    return true
  }

  return (
    <div style={{ padding: '24px', minHeight: '100vh', backgroundColor: '#f5f5f5' }}>
      <style>{`
        .edit-modal-image-container:hover .edit-modal-image-overlay {
          opacity: 1 !important;
        }
        
        .edit-modal-image-overlay > div:hover {
          transform: scale(1.1);
          transition: transform 0.1s ease;
        }
        
        .add-image-button:hover {
          border-color: #1890ff !important;
          color: #1890ff !important;
          background-color: #e6f7ff !important;
        }
      `}</style>
      
      {/* 面包屑导航 */}
      <div style={{ marginBottom: '24px' }}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <HomeOutlined 
              onClick={() => navigate('/home')} 
              style={{ cursor: 'pointer', color: '#1890ff' }}
            />
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <span 
              onClick={() => navigate('/storyboard')} 
              style={{ cursor: 'pointer', color: '#1890ff' }}
            >
              分镜管理
            </span>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <span 
              onClick={() => navigate(`/storyboard/project/${projectId}`)} 
              style={{ cursor: 'pointer', color: '#1890ff' }}
            >
              分镜制作
            </span>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <FileTextOutlined />
            故事板视图
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>

      {/* 页面标题 */}
      <div style={{ marginBottom: '32px', textAlign: 'center' }}>
        <Title level={2}>{project?.name || '故事板视图'}</Title>
        <p style={{ color: '#666', fontSize: '16px' }}>
          以视觉化方式展示分镜内容，便于整体把控故事节奏
        </p>
      </div>

      {/* 故事板卡片网格 */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: '60px 0' }}>
          <Card loading style={{ maxWidth: '300px', margin: '0 auto' }}>
            <div style={{ height: '100px' }}></div>
          </Card>
        </div>
      ) : storyboardCards.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '60px 0' }}>
          <Card style={{ maxWidth: '400px', margin: '0 auto' }}>
            <div style={{ padding: '40px 20px' }}>
              <div style={{ fontSize: '16px', color: '#666', marginBottom: '16px' }}>
                暂无分镜内容
              </div>
              <div style={{ fontSize: '14px', color: '#999', marginBottom: '20px' }}>
                请先在分镜制作页面添加场景内容
              </div>
              <Button type="primary" onClick={() => navigate(`/storyboard/project/${projectId}`)}>
                前往分镜制作
              </Button>
            </div>
          </Card>
        </div>
      ) : (
        <Row gutter={[16, 16]}>
          {storyboardCards.map((card, index) => (
            <Col xs={24} sm={12} md={8} lg={6} xl={4} key={card.id}>
              <Card
                hoverable
                style={{ 
                  height: '380px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                  borderRadius: '8px',
                  border: '1px solid #f0f0f0',
                  position: 'relative'
                }}
                bodyStyle={{ padding: '12px', position: 'relative' }}
                cover={
                  <div style={{ 
                    height: '220px', 
                    backgroundColor: '#f8f9fa',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    position: 'relative',
                    overflow: 'hidden',
                    border: 'none'
                  }}>
                    {card.image ? (
                      <img
                        alt={card.title}
                        src={card.image}
                        style={{ 
                          width: '100%', 
                          height: '100%', 
                          objectFit: 'cover',
                          cursor: 'pointer'
                        }}
                        onClick={() => handleImagePreview(card.image!)}
                      />
                    ) : (
                      <Upload
                        accept="image/*"
                        showUploadList={false}
                        beforeUpload={(file) => handleImageUpload(card.id, file)}
                        style={{ width: '100%', height: '100%' }}
                      >
                        <div style={{
                          width: '100%',
                          height: '220px',
                          display: 'flex',
                          flexDirection: 'column',
                          alignItems: 'center',
                          justifyContent: 'center',
                          cursor: 'pointer',
                          color: '#bbb',
                          fontSize: '14px'
                        }}>
                          <PlusOutlined style={{ fontSize: '20px', marginBottom: '6px' }} />
                          <div>未添加图片</div>
                        </div>
                      </Upload>
                    )}
                    
                    {/* 镜头编号 */}
                    <div style={{
                      position: 'absolute',
                      top: '8px',
                      left: '8px',
                      backgroundColor: 'rgba(0,0,0,0.75)',
                      color: 'white',
                      padding: '3px 6px',
                      borderRadius: '3px',
                      fontSize: '11px',
                      fontWeight: 'bold'
                    }}>
                      镜头{index + 1}
                    </div>
                  </div>
                }
              >
                {/* 景别和时长信息 */}
                <div style={{ 
                  display: 'flex', 
                  justifyContent: 'space-between', 
                  alignItems: 'center',
                  marginBottom: '8px',
                  fontSize: '12px',
                  color: '#666'
                }}>
                  <span style={{ fontWeight: '500' }}>{card.shotType}</span>
                  <span>{card.duration}秒</span>
                </div>
                
                {/* 内容描述 */}
                <div style={{ 
                  fontSize: '13px', 
                  color: '#333',
                  lineHeight: '1.4',
                  minHeight: '40px',
                  overflow: 'hidden',
                  display: '-webkit-box',
                  WebkitLineClamp: 3,
                  WebkitBoxOrient: 'vertical'
                }}>
                  {card.content}
                </div>

                {/* 编辑按钮 - 位于卡片右下角 */}
                <Button
                  type="text"
                  size="small"
                  icon={<EditOutlined />}
                  onClick={(e) => {
                    e.stopPropagation()
                    handleEditCard(card.id)
                  }}
                  style={{
                    position: 'absolute',
                    bottom: '8px',
                    right: '8px',
                    backgroundColor: 'rgba(255,255,255,0.95)',
                    border: '1px solid #d9d9d9',
                    color: '#666',
                    width: '28px',
                    height: '28px',
                    borderRadius: '6px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                    zIndex: 10
                  }}
                />
              </Card>
            </Col>
          ))}
        </Row>
      )}

      {/* 图片预览弹窗 */}
      <Modal
        open={previewVisible}
        title="图片预览"
        footer={null}
        onCancel={() => setPreviewVisible(false)}
        width="80%"
        style={{ top: 20 }}
      >
        <img
          alt="预览"
          style={{ width: '100%' }}
          src={previewImage}
        />
      </Modal>

      {/* 编辑弹窗 */}
      <Modal
        title={`编辑镜头 ${currentEditCard ? storyboardCards.findIndex(c => c.id === currentEditCard.id) + 1 : ''}`}
        open={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={() => {
          setEditModalVisible(false)
          setCurrentEditCard(null)
        }}
        okText="确认"
        cancelText="取消"
        width={600}
        centered
      >
        <div style={{ padding: '20px 0' }}>
          {/* 图片展示区域 */}
          <div style={{ 
            marginBottom: '20px'
          }}>
            <div style={{ marginBottom: '8px', fontSize: '14px', fontWeight: 500 }}>画面图片</div>
            
            <div style={{ 
              display: 'flex',
              alignItems: 'flex-start',
              gap: '12px',
              flexWrap: 'wrap'
            }}>
              {/* 现有图片展示 */}
              {currentEditCard?.images && currentEditCard.images.length > 0 && 
                currentEditCard.images.map((imageUrl, index) => (
                  <div 
                    key={index}
                    className="edit-modal-image-container"
                    style={{ 
                      position: 'relative',
                      width: '160px',
                      height: '100px',
                      border: '2px solid #e8e8e8',
                      borderRadius: '8px',
                      overflow: 'hidden',
                      cursor: 'pointer'
                    }}
                  >
                    <img 
                      src={imageUrl}
                      alt={`镜头画面 ${index + 1}`}
                      style={{ 
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover'
                      }}
                    />
                    
                    {/* 图片编号标识 */}
                    <div style={{
                      position: 'absolute',
                      top: '4px',
                      left: '4px',
                      backgroundColor: 'rgba(0,0,0,0.7)',
                      color: 'white',
                      padding: '2px 6px',
                      borderRadius: '3px',
                      fontSize: '10px',
                      fontWeight: 'bold'
                    }}>
                      {index + 1}
                    </div>
                    
                    {/* 悬浮操作层 */}
                    <div style={{
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      right: 0,
                      bottom: 0,
                      background: 'rgba(0, 0, 0, 0.6)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      gap: '6px',
                      opacity: 0,
                      transition: 'opacity 0.2s ease',
                    }}
                    className="edit-modal-image-overlay"
                    >
                      <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        color: 'white',
                        cursor: 'pointer',
                        fontSize: '10px'
                      }}
                      onClick={(e) => {
                        e.stopPropagation()
                        handleEditModalImagePreview(imageUrl)
                      }}
                      >
                        <EyeOutlined style={{ fontSize: '12px', marginBottom: '1px' }} />
                        <span>预览</span>
                      </div>
                      
                      <div
                        style={{
                          display: 'flex',
                          flexDirection: 'column',
                          alignItems: 'center',
                          color: 'white',
                          cursor: 'pointer',
                          fontSize: '10px'
                        }}
                        onClick={(e) => {
                          console.log('[故事板视图] 替换按钮被点击，索引:', index)
                          e.stopPropagation()
                          handleImageReplaceClick(index)
                        }}
                      >
                        <UploadOutlined style={{ fontSize: '12px', marginBottom: '1px' }} />
                        <span>替换</span>
                      </div>
                      
                      <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        color: '#ff4d4f',
                        cursor: 'pointer',
                        fontSize: '10px'
                      }}
                      onClick={(e) => {
                        e.stopPropagation()
                        handleEditModalImageRemove(index)
                      }}
                      >
                        <CloseOutlined style={{ fontSize: '12px', marginBottom: '1px' }} />
                        <span>删除</span>
                      </div>
                    </div>
                  </div>
                ))
              }
              
              {/* 添加图片按钮 */}
              <div
                style={{
                  width: '160px',
                  height: '100px',
                  border: '2px dashed #d9d9d9',
                  borderRadius: '8px',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                  backgroundColor: '#fafafa',
                  color: '#bfbfbf',
                  fontSize: '12px',
                  transition: 'all 0.2s ease'
                }}
                className="add-image-button"
                onClick={() => {
                  console.log('[故事板视图] 添加图片按钮被点击')
                  handleAddImageClick()
                }}
              >
                <PlusOutlined style={{ fontSize: '18px', marginBottom: '4px' }} />
                <div>添加图片</div>
              </div>
            </div>
            
            {/* 图片数量提示 */}
            {currentEditCard?.images && currentEditCard.images.length > 0 && (
              <div style={{ 
                marginTop: '8px', 
                fontSize: '12px', 
                color: '#666' 
              }}>
                已添加 {currentEditCard.images.length} 张图片
              </div>
            )}
          </div>
          
          <Form layout="vertical">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="景别">
                  <Select
                    value={editForm.shotType}
                    onChange={(value) => setEditForm(prev => ({ ...prev, shotType: value }))}
                    style={{ width: '100%' }}
                  >
                    <Select.Option value="远景">远景</Select.Option>
                    <Select.Option value="全景">全景</Select.Option>
                    <Select.Option value="中远景">中远景</Select.Option>
                    <Select.Option value="中景">中景</Select.Option>
                    <Select.Option value="中近景">中近景</Select.Option>
                    <Select.Option value="近景">近景</Select.Option>
                    <Select.Option value="特写">特写</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="时长（秒）">
                  <InputNumber
                    min={1}
                    max={3600}
                    value={editForm.duration}
                    onChange={(value) => setEditForm(prev => ({ ...prev, duration: value || 5 }))}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
            </Row>
            
            <Form.Item label="内容">
              <Input.TextArea
                rows={4}
                value={editForm.content}
                onChange={(e) => setEditForm(prev => ({ ...prev, content: e.target.value }))}
                placeholder="请输入镜头内容描述"
              />
            </Form.Item>
            
            <Form.Item label="声音">
              <Input.TextArea
                rows={3}
                value={editForm.voiceOver}
                onChange={(e) => setEditForm(prev => ({ ...prev, voiceOver: e.target.value }))}
                placeholder="请输入旁白或音效描述"
              />
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </div>
  )
}

export default StoryboardViewPage